package com.sh.lock;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Auther: sh
 * @Version 1.0
 * @Description:
 */
public class StudyLock {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(ticket, "窗口1").start();
        new Thread(ticket, "窗口2").start();
        new Thread(ticket, "窗口3").start();
    }
}

class Ticket implements Runnable {

    private final ReentrantLock lock = new ReentrantLock(true);
    private AtomicInteger ticketNums = new AtomicInteger(10);
    @Override
    public void run() {
        while (true) {
            int currentTicket = ticketNums.get();
            if (currentTicket <= 0) {
                break;
            }
            // 用 compareAndSet 保证更新时不会被覆盖
            if (ticketNums.compareAndSet(currentTicket, currentTicket - 1)) {
                System.out.println(Thread.currentThread().getName() + " 拿到票，票号为 " + currentTicket);
                try {
                    Thread.sleep(10); // 模拟出票时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 如果 compareAndSet 失败，说明其他线程抢先一步，重试即可
        }
    }

//    @Override
//    public void run() {
//        while (true) {
//            lock.lock();
//            try {
//                if (ticketNums > 0) {
//                    Thread.sleep(100); // 模拟出票时间
//                    System.out.println(Thread.currentThread().getName() + " 拿到票，票号为 " + ticketNums--);
//                } else {
//                    break; // ✅ 跳出 while 循环，但线程完整执行完
//                }
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            } finally {
//                lock.unlock(); // ✅ 永远释放锁
//            }
//        }
//    }

}

